<?php

       // Database Initialize
	$bgcolor = Array('#CECECE', '#EEEEEE');
	//$bgcolor = Array('#FFFFFF', '#FFFFFF');
	class  LoadFile
	{
		// define the properties
		var $strContent;
		var $error = 0;

		// define the methods
		function LoadFile($Filename)
		{
			if (file_exists($Filename))
			{
				$file = fopen($Filename,"r");
				$this->strContent = fread($file,filesize($Filename));
			}
			else
			{
				$this->error = 1;
				return;
			}
		}

	} 	// end of LoadFile class

    // examples :

    /*
	--------------------------------------------------------
	$Test = new LoadFile("test.html");
	if ($Test->error) {
		echo ("Error: Can\'t load file.");
	}
	else
	{
		$Content = $Test->strContent;
		print($Content);

	}
	-------------------------------------------------------
    */

	function loadHtml($htm_file, $msg="")
	{
		$template = new LoadFile($htm_file);
		if($template->error){
			return "Error: Can't load the template file ($htm_file) .";
			exit();
		}
		$content = $template->strContent;
		$content = ereg_replace("@msg@",$msg, $content);
		return $content;
	}

	function get_file($filename){

		if($fp = fopen($filename, 'rb')){
			$return = fread($fp, filesize($filename));
			fclose($fp);
			return $return;
		}else
			return FALSE;
	}

	function sendmail($to,$from,$d_from='',$subject,$data)
	{
		if(!$to ||!$from || !$subject || !$data) return false;
		if(!defined('CRLF')) define('CRLF', "\r\n", TRUE);

		$headers = "MIME-Version: 1.0".CRLF;
		if($d_from) $headers .= "From: $d_from <$from>".CRLF;
		else $headers .= "From: $from".CRLF;
		$headers .= "Content-type: text/html charset=iso-8859-1".CRLF;
		$headers .= "Content-Transfer-Encoding: 8bit".CRLF;

		return mail($to, $subject, $data, $headers);
	}

	function scan_dir($pathdir)
	{
		$result = "";
		if($dir = @opendir($pathdir))
		{
			while ($file = readdir($dir)) {
				if(substr($file,0,1)!="." && filetype($file)!="dir")
					$result .= "<option value='$pathdir/$file'>$file</option>\n";

			}
			closedir($dir);
		}
		return $result;
	}

//Return String is replaced with para_cmp to para_url
	function replace_link($data, $para_cmp="", $para_url="")
	{
	//Example parameters:
	//	$para_cmp = "src=";
	//	$para_url = "http://host_server/maillist/ads/13/images/";
	//	$data = get_file("content.php");
	//	echo substr_count($data, $para_cmp)."<br>";

		if(!$para_url || !$para_cmp) return false;
	//---------------------------------------------
		$result = $cur = $data;
		$len = strlen($cur);
		$arr_source;
		$arr_dest;

		//Get position of para_cmp
		$i=0;
		while ($i<$len)
		{
			$cur = substr($cur,1,$len-1);
			$i = strpos(strtolower($cur),strtolower($para_cmp));
			$cur = substr($cur,$i,$len-$i);
			$len = strlen($cur);

			if($i)
			{
				//Get position of end of string
				$chr = substr($cur,$j=0,1);
				while(($chr!='>' && $chr!=' ') && ($j<=(strlen($para_cmp)+1) || ($chr!='"' && $chr!="'")) && $j<$len)
				{
					$j++ ;
					$chr = substr($cur,$j,1);
				}

				//Store source Link
				$arr_source[] = substr($cur,0,$j+1);

				//Get base file name
				$base_str = substr($cur,0,$j);
				$base_str = str_replace('"',"",$base_str);
				$base_str = str_replace($para_cmp,"",$base_str);
				$base_str = basename($base_str);

				//Store new link
				$arr_dest[] = "$para_cmp\"$para_url$base_str\"";
			}
		}

		//End Result
		for($i=0; $i<sizeof($arr_source); $i++)
		{
			$result = str_replace($arr_source[$i],$arr_dest[$i],$result);
			//echo $arr_source[$i] . " => ". $arr_dest[$i] . "<br>";
		}
		return $result;
	}

//convert link
	function html_links($str)
	{
		$str = eregi_replace("([^=\"'>])((f|ht)tp:\/\/[a-z0-9~#%@\&:=?\/\._-]+[a-z0-9~#%@\&=?\/_-]+)", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $str); //http
		$str = eregi_replace("([^=/\"'>])(www\.[a-z0-9~#%@\&:=?\/\._-]+[a-z0-9~#%@\&=?\/_-]+)", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $str); // www.
		$str = eregi_replace("([^=\"':>])([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})","<a href=\"mailto:\\1\\2\">\\1\\2</a>", $str); // mail
		$str = eregi_replace("^((f|ht)tp:\/\/[a-z0-9~#%@\&:=?\/\._-]+[a-z0-9~#%@\&=?\/_-]+)", "<a href=\"\\1\" target=\"_blank\">\\1</a>", $str); //http
		$str = eregi_replace("^(www\.[a-z0-9~#%@\&:=?\/\._-]+[a-z0-9~#%@\&=?\/_-]+)", "<a href=\"http://\\1\" target=\"_blank\">\\1</a>", $str); // www.
		$str = eregi_replace("^([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})","<a href=\"mailto:\\1\">\\1</a>", $str); // mail
		return $str;
	}


//--------------------------For MYSQL

	function del_dir($pathdir)
	{
		if($dir = @opendir($pathdir))
		{
			while ($file = readdir($dir)) {
				if(substr($file,0,1)!="." && filetype($file)!="dir") unlink("$pathdir/$file");
			}
			closedir($dir);
			if(is_dir($pathdir)) rmdir($pathdir);
		}
	}

	function delete_dir($db,$upload_path,$projectid)
	{
		del_dir($upload_path.$projectid."/cl");
		del_dir($upload_path.$projectid."/images");
		del_dir($upload_path.$projectid);
		$query = "DELETE from files where PROJECTID=$projectid";
		mysql_query($query,$db);
	}


//Get value of any field of any table
	function get_field($table="",$field="",$value="",$g_field="")
	{

   	    $db_gefield = new my_db;
        $db_gefield->open(DATABASE_HOST,DATABASE_USER,DATABASE_PASSWORD,DATABASE_NAME,DBSTYLE);

		if ($field != "" && $table!="" && $g_field!="")
		{
			if(is_numeric($value))
				$strSql = "select $g_field from $table where $field = $value";
			else
				$strSql = "select $g_field from $table where $field like '$value'";
//			$rs = mysql_query($strSql,$db_gefield);
//			if ( $row = mysql_fetch_array($rs) ){
			$stmt= new db_query($db_gefield,$strSql);
			if ($stmt->getrow()){
				$g_field = $stmt->row[0];
			}
			else {
				$g_field = "";
			}
//			mysql_free_result($rs);
			return $g_field;
		}
		else return "";
	}
	
	function get_value($sql="")
	{
   	    $db_value = new my_db;
        $db_value->open(DATABASE_HOST,DATABASE_USER,DATABASE_PASSWORD,DATABASE_NAME,DBSTYLE);

		if ($sql != "")
		{
			$stmt= new db_query($db_value,$sql);
			if ($stmt->getrow()){
				$g_value = $stmt->row[0];
			}
			else {
				$g_value = "";
			}
			return $g_value;
		}
		else return "";
	}	
	
//Get value from session
function get_param($param_name)
{
  global $HTTP_POST_VARS;
  global $HTTP_GET_VARS;

  $param_value = "";
  if(isset($HTTP_POST_VARS[$param_name]))
    $param_value = $HTTP_POST_VARS[$param_name];
  else if(isset($HTTP_GET_VARS[$param_name]))
    $param_value = $HTTP_GET_VARS[$param_name];

  return $param_value;
}

function get_session($param_name)
{
  global $HTTP_POST_VARS;
  global $HTTP_GET_VARS;
  global ${$param_name};

  $param_value = "";
  if(!isset($HTTP_POST_VARS[$param_name]) && !isset($HTTP_GET_VARS[$param_name]) && session_is_registered($param_name))
    $param_value = ${$param_name};

  return $param_value;
}

function set_session($param_name, $param_value)
{
  global ${$param_name};
  if(session_is_registered($param_name))
    session_unregister($param_name);
  ${$param_name} = $param_value;
  session_register($param_name);
}

function tourl($strValue)
{
  return urlencode($strValue);
}

function tosql($value, $type)
{
    if($type == "Number")
      return doubleval($value);
    else
    {
      if(get_magic_quotes_gpc() == 0)
      {
        $value = str_replace("'","''",$value);
        $value = str_replace("\\","\\\\",$value);
      }
      else
      {
        $value = str_replace("\\'","''",$value);
        $value = str_replace("\\\"","\"",$value);
      }

      return "'" . $value . "'";
    }
}

/////////////////////////
//- function returns options for HMTL control "<select>" as one string
function get_options($sql,$is_search,$is_required,$selected_value)
{

	  $options_str="";
	  if ($is_search)
		$options_str.="<option value=\"\">All</option>";
	  else
	  {
		if (!$is_required)
		{
		  $options_str.="<option value=\"\">----------</option>";
		}
	  }

	//$result =  $db2->query($sql);
	//while ($row=mysql_fetch_array($result))

	$db_option = new my_db;
	$db_option->open(DATABASE_HOST,DATABASE_USER,DATABASE_PASSWORD,DATABASE_NAME,DBSTYLE);
	$stmt_option= new db_query($db_option,$sql);
	while ($stmt_option->getrow())
	  {
	//    $id=$row[0];
		$id = $stmt_option->row[0];
		$value=$stmt_option->row[1];
		$selected="";
		if ($id == $selected_value)
		{
		  $selected = "SELECTED";
		}
		$options_str.= "<option value='".$id."' ".$selected.">".$value."</option> \n";
	  }

		return $options_str;
	//	return $sql;
//		return $ketqua;
}

//Duc Manh add 14/03/2004
// chi liet ke cac <option> </option>
function get_options_row($sql, $selected_value)
{

	$options_str="";
	$db_option = new my_db;
	$db_option->open(DATABASE_HOST,DATABASE_USER,DATABASE_PASSWORD,DATABASE_NAME,DBSTYLE);
	$stmt_option= new db_query($db_option,$sql);
	while ($stmt_option->getrow())
	  {
		$id = $stmt_option->row[0];
		$value=$stmt_option->row[1];
		$selected="";
		if ($id == $selected_value)
		{
		  $selected = "SELECTED";
		}
		$options_str.= "<option value='".$id."' ".$selected.">".$value."</option> \n";
	  }
		return $options_str;
}

function get_options_array($arr,$is_search,$is_required,$selected_value)
{
	$options_str="";
	if ($is_search){
		$options_str.="<option value=\"\">All</option>";
	}else{
		if (!$is_required){
			$options_str.="<option value=\"\">----------</option>";
		}
	}

	foreach($arr as $id=>$value) {
		//$id = $i;
		//$value=$arr[$i];
		//echo "id: $id - value : $value<br>";
		$selected="";
		if ($id == $selected_value){
		  $selected = "SELECTED";
		}
		$options_str.= "<option value='".$id."' ".$selected.">".$value."</option> \n";
	}

		return $options_str;
}


//Delete data if relationship is null
	function defrag($db,$table="",$parent_tbl="",$parent_fk="",$condition="")
	{
		if ($table!="" && $parent_tbl!="" && $parent_fk!="")
		{
			$collect = "";
			$started = false;
			$strSql = "select $parent_fk from $parent_tbl where $parent_fk is not null";
			if ($condition != "") $strSql .= " and $condition";
			$rs = mysql_query($strSql,$db);
			while ($row = mysql_fetch_array($rs))
			{	if ($started) $collect .= ",";
				else $started = true;
				$collect.=$row[$parent_fk];
			}
			mysql_free_result($rs);
			if ($collect!="") mysql_query("delete from $table where $parent_fk not in ($collect)");
			else mysql_query("delete from $table");
		}
	}


//Duc Manh : 25/09/2003
//Ham liet ke cac trang
    function list_page($which_page=0,$num_page=0,$page_block=0,$StringQuery="")
    {
            $first_page = 0;
            $last_page = 0;
            $page_block = $page_block - 1;

			if ($num_page<=$page_block)
            {
                $first_page=1;
                $last_page=$num_page;
            }
            else
            {
                if (($which_page+$page_block) < $num_page)
                {
                    $first_page=$which_page ;
                    $last_page=$which_page+$page_block;
                }
                else
                {
                    $first_page=$num_page-$page_block ;
                    $last_page=$num_page;
                }
            }

	        for ($i = $first_page; $i <= $last_page; $i++) {
	        if ($i==$which_page) {
	            $str_paging .= "<b>&nbsp;".$i."</b>";
	        }
	        else{
	            $str_paging .= "&nbsp;<a href=\"?which_page=".$i.$StringQuery."><u>".$i."</u></a>";
	        }//End if $i==$which_page
	    } //end for $i=1 to $num_pages
        return $str_paging;
    }

//Duc Manh Edit : 23/03/2004
//Ham liet ke cac trang
    function list_page_css($which_page=0,$num_page=0,$page_block=0,$StringQuery="", $filelink="", $var_page="which_page")
    {
            $first_page = 0;
            $last_page = 0;
            $page_block = $page_block - 1;

			if ($num_page<=$page_block)
            {
                $first_page=1;
                $last_page=$num_page;
            }
            else
            {
                if (($which_page+$page_block) < $num_page)
                {
                    $first_page=$which_page ;
                    $last_page=$which_page+$page_block;
                }
                else
                {
                    $first_page=$num_page-$page_block ;
                    $last_page=$num_page;
                }
            }

	        for ($i = $first_page; $i <= $last_page; $i++) {
	        if ($i==$which_page) {
	            $str_paging .= "&nbsp;<span class=listpage_nolink>".$i."</span>";
	        }
	        else{
	            $str_paging .= "&nbsp;<a class='listpage' href=\"$filelink?$var_page=".$i.$StringQuery.">".$i."</a>";
	        }//End if $i==$which_page
	    } //end for $i=1 to $num_pages
        return $str_paging;
    }

 //Tra ve 1 gia tri tu Database
function get_field_value($s_SQL)
{
	//  global $db2;  //-- connection special for list box
/*	$db2 = new DB_Sql();
	$db2->Database = $DBNAME;
	$db2->User     = $DBUSER;
	$db2->Password = $DBPASSWORD;
	$db2->Host     = $DBHOST;
*/
	$dbconnf = new my_db;
	$dbconnf->open(DATABASE_HOST,DATABASE_USER,DATABASE_PASSWORD,DATABASE_NAME,DBSTYLE);
   	$stmt= new db_query($dbconnf,$s_SQL);
if ($stmt->getrow())
	return $stmt->row[0];

}

//NDM add 17/10/2003
//Ham bao mat - kiem tra quyen truy xuat
function check_security($iLevel)
{
	global $UserRights;
	$url = "";
	if(!session_is_registered("UserID"))
	{
		//print "Not UserID"; //Debug
			$url = "login.php?querystring=" . tourl(getenv("QUERY_STRING")) . "&ret_page=" . tourl(getenv("REQUEST_URI"));
	}
	else
	{
		if(!session_is_registered("UserRights") || $UserRights > $iLevel)
		{
 			$url = "login.php?querystring=" . tourl(getenv("QUERY_STRING")) . "&ret_page=" . tourl(getenv("REQUEST_URI"));
		}
	}
	if ($url != ""){
		echo "<script>document.location='".$url."'</script>";
	}
}

function check_security_1($iLevel)
{
	global $UserRights;
	$url = "";
	$url_begin = "http://".HOST_DOMAIN_NAME.ROOT_WS.'admin/php/';
	if(!session_is_registered("UserID"))
	{
		//print "Not UserID"; //Debug
			$url = $url_begin."login.php?querystring=" . tourl(getenv("QUERY_STRING")) . "&ret_page=" . tourl(getenv("REQUEST_URI"));
	}
	else
	{
		if(!session_is_registered("UserRights") || $UserRights > $iLevel)
		{
 			$url = $url_begin."login.php?querystring=" . tourl(getenv("QUERY_STRING")) . "&ret_page=" . tourl(getenv("REQUEST_URI"));
		}
	}
	if ($url != ""){
		//echo "$url";
		//*
		echo "<script>document.location='".$url."'</script>";
		//*/
	}
}


function get_date_dmy($date)
{
	$return_result = "";
	if (is_string( $date))
	{
		$return_result = substr($date,8,2)."-".substr($date,5,2)."-".substr($date,0,4);
	}
	else
	{
		$return_result = $date;
	}
	return $return_result;
}
 
function get_date_mdy($date)
{
	$return_result = "";
	if (is_string( $date))
	{
		$return_result = substr($date,5,2)."-".substr($date,8,2)."-".substr($date,0,4);
	}
	else
	{
		$return_result = $date;
	}
	return $return_result;
}
 

/*******************************
* Duc Manh add 13/5/2005
*******************************/
class  TreeMenu
{
	// define the properties
	var $ketqua = "";
	var $Tree = array();	

	// define the methods
    function TreeMenu() {
      
    }	
	
	function get_nodes($rootid, $root_level )
	{
		$Counter = 0;
		$LastLevel = get_values("select max(cat_level) from cat");
		$this->fill ($rootid, $root_level);	
		$total = count($this->Tree);
		$j=1;
		while (list($key,) = each($this->Tree)) 
		{ 
			if ($j < $total){
			   $this->ketqua .= $this->Tree[$key].", ";
			}
			else{
				$this->ketqua .= $this->Tree[$key];
			}
		   $j++;
		}
		$this->ketqua = "(".$this->ketqua.")";
		return $this->ketqua;
	}

	function fill($StartId, $Lev)
	{
		global $dbconn, $LastLevel, $Counter;
		
		//echo "Counter: $Counter<br>";
		$Counter++;
		$this->Tree[$Counter] = $StartId;
		if( $Lev == $LastLevel)
		{
			return "";
		}
		$_Lev = $Lev + 1;
		$sql_num_sub = "SELECT count(*) FROM cat WHERE cat_parent='$StartId' and cat_level='$_Lev'";
		//echo "sql_num_sub: $sql_num_sub<br>";
		$num_sub = get_values($sql_num_sub);
		
		if ($num_sub == 0) 
		{
			return "";
		}


		$strSQL = "SELECT * FROM cat WHERE cat_parent='$StartId' and cat_level='$_Lev'";

		$db_fill = new my_db;
		$db_fill->open(DATABASE_HOST,DATABASE_USER,DATABASE_PASSWORD,DATABASE_NAME,DBSTYLE);
		$stmt= new db_query($db_fill,$strSQL);		
		
		//echo "strSQL: $strSQL<br>";

		while ($stmt->getrow())
		{					 
			$subcatid = $stmt->row["catid"];
			//echo "subcatid: $subcatid<br>";
			$this->fill ($subcatid, $Lev + 1);		
		}			
	}
} 	// end of TreeMenu class
 
?>